package com.clouddms.service.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 服务管理器
 * 负责注册、管理和监控所有Cloud-DMS服务
 *
 * @author Cloud-DMS Team
 * @version 1.0.0
 */
@Slf4j
@Component
public class ServiceManager {

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 服务注册表 - 使用ConcurrentHashMap确保线程安全
     */
    private final Map<String, IService> serviceRegistry = new ConcurrentHashMap<>();

    /**
     * 服务状态缓存
     */
    private final Map<String, ServiceStatus> statusCache = new ConcurrentHashMap<>();

    /**
     * 初始化服务管理器
     */
    @PostConstruct
    public void initialize() {
        log.info("正在初始化ServiceManager...");

        // 自动发现并注册所有实现了IService的服务
        Map<String, IService> services = applicationContext.getBeansOfType(IService.class);

        for (Map.Entry<String, IService> entry : services.entrySet()) {
            registerService(entry.getValue());
        }

        log.info("ServiceManager初始化完成，已注册 {} 个服务", serviceRegistry.size());
    }

    /**
     * 注册服务
     */
    public void registerService(IService service) {
        String serviceName = service.getServiceName();
        serviceRegistry.put(serviceName, service);
        updateServiceStatus(serviceName, service.getStatus());

        log.info("服务已注册: {} [{}] - {}",
                service.getDisplayName(),
                service.getStatus().getDisplayName(),
                service.getDescription());
    }

    /**
     * 卸载服务
     */
    public void unregisterService(String serviceName) {
        IService service = serviceRegistry.remove(serviceName);
        statusCache.remove(serviceName);

        if (service != null) {
            log.info("服务已卸载: {}", service.getDisplayName());
        }
    }

    /**
     * 获取服务
     */
    public Optional<IService> getService(String serviceName) {
        return Optional.ofNullable(serviceRegistry.get(serviceName));
    }

    /**
     * 获取所有服务
     */
    public List<IService> getAllServices() {
        return serviceRegistry.values()
                .stream()
                .sorted(Comparator.comparingInt(IService::getPriority))
                .collect(Collectors.toList());
    }

    /**
     * 获取服务状态信息
     */
    public Map<String, Object> getServiceStatusInfo() {
        Map<String, Object> statusInfo = new HashMap<>();

        for (IService service : getAllServices()) {
            Map<String, Object> serviceInfo = new HashMap<>();
            serviceInfo.put("name", service.getServiceName());
            serviceInfo.put("displayName", service.getDisplayName());
            serviceInfo.put("description", service.getDescription());
            serviceInfo.put("status", service.getStatus().name());
            serviceInfo.put("statusDisplay", service.getStatus().getDisplayName());
            serviceInfo.put("statusColor", service.getStatus().getColor());
            serviceInfo.put("version", service.getVersion());
            serviceInfo.put("available", service.isAvailable());
            serviceInfo.put("priority", service.getPriority());

            // 健康状态
            IService.HealthStatus health = service.getHealthStatus();
            serviceInfo.put("healthy", health.isHealthy());
            serviceInfo.put("healthMessage", health.getMessage());

            statusInfo.put(service.getServiceName(), serviceInfo);
        }

        return statusInfo;
    }

    /**
     * 更新服务状态
     */
    public void updateServiceStatus(String serviceName, ServiceStatus status) {
        statusCache.put(serviceName, status);
        log.debug("服务状态已更新: {} -> {}", serviceName, status.getDisplayName());
    }

    /**
     * 获取系统整体状态
     */
    public SystemStatus getSystemStatus() {
        List<IService> services = getAllServices();

        int total = services.size();
        long running = services.stream().mapToLong(s -> s.getStatus() == ServiceStatus.RUNNING ? 1 : 0).sum();
        long debugging = services.stream().mapToLong(s -> s.getStatus() == ServiceStatus.DEBUGGING ? 1 : 0).sum();
        long developing = services.stream().mapToLong(s -> s.getStatus() == ServiceStatus.DEVELOPING ? 1 : 0).sum();
        long mocking = services.stream().mapToLong(s -> s.getStatus() == ServiceStatus.MOCKING ? 1 : 0).sum();

        return new SystemStatus(total, (int)running, (int)debugging, (int)developing, (int)mocking);
    }

    /**
     * 获取服务状态摘要
     */
    public Map<String, Object> getServiceStatusSummary() {
        SystemStatus systemStatus = getSystemStatus();
        Map<String, Object> summary = new HashMap<>();
        
        summary.put("totalServices", systemStatus.getTotalServices());
        summary.put("runningServices", systemStatus.getRunningServices());
        summary.put("debuggingServices", systemStatus.getDebuggingServices());
        summary.put("developingServices", systemStatus.getDevelopingServices());
        summary.put("mockingServices", systemStatus.getMockingServices());
        summary.put("readinessPercentage", systemStatus.getReadinessPercentage());
        
        return summary;
    }

    /**
     * 获取所有服务信息
     */
    public List<Map<String, Object>> getAllServiceInfo() {
        List<Map<String, Object>> serviceList = new ArrayList<>();
        
        for (IService service : getAllServices()) {
            Map<String, Object> serviceInfo = new HashMap<>();
            serviceInfo.put("name", service.getServiceName());
            serviceInfo.put("displayName", service.getDisplayName());
            serviceInfo.put("description", service.getDescription());
            serviceInfo.put("status", service.getStatus().name());
            serviceInfo.put("statusDisplay", service.getStatus().getDisplayName());
            serviceInfo.put("statusColor", service.getStatus().getColor());
            serviceInfo.put("version", service.getVersion());
            serviceInfo.put("available", service.isAvailable());
            serviceInfo.put("priority", service.getPriority());

            // 健康状态
            IService.HealthStatus health = service.getHealthStatus();
            serviceInfo.put("healthy", health.isHealthy());
            serviceInfo.put("healthMessage", health.getMessage());
            
            serviceList.add(serviceInfo);
        }
        
        return serviceList;
    }

    /**
     * 系统状态统计
     */
    public static class SystemStatus {
        private final int totalServices;
        private final int runningServices;
        private final int debuggingServices;
        private final int developingServices;
        private final int mockingServices;

        public SystemStatus(int total, int running, int debugging, int developing, int mocking) {
            this.totalServices = total;
            this.runningServices = running;
            this.debuggingServices = debugging;
            this.developingServices = developing;
            this.mockingServices = mocking;
        }

        // Getters
        public int getTotalServices() { return totalServices; }
        public int getRunningServices() { return runningServices; }
        public int getDebuggingServices() { return debuggingServices; }
        public int getDevelopingServices() { return developingServices; }
        public int getMockingServices() { return mockingServices; }

        public double getReadinessPercentage() {
            if (totalServices == 0) return 0.0;
            return (double)(runningServices + debuggingServices) / totalServices * 100;
        }
    }
}